<template>
  <a-card class="j-inner-table-wrapper" :bordered="false">

    <!-- 查询区域 begin -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="单位">
              <j-dict-select-tag v-model="queryParam.unit" placeholder="请选择单位" dictCode="unit" />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="年度">
              <j-dict-select-tag v-model="queryParam.year" placeholder="请选择年度" dictCode="year" />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span class="table-page-search-submitButtons table-operator">
              <a-button type="primary" icon="search" @click="searchQuery">查询</a-button>
              <a-button type="primary" icon="reload" @click="searchReset">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                <span>{{ toggleSearchStatus ? '收起' : '展开' }}</span>
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域 end -->

    <!--    &lt;!&ndash; 操作按钮区域 begin &ndash;&gt;-->
    <!--    <div class="table-operator">-->
    <!--      <a-button type="primary" icon="plus" @click="handleAdd">新增</a-button>-->
    <!--      <a-button type="primary" icon="download" @click="handleExportXls('公用经费支出提交表')">导出</a-button>-->
    <!--      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">-->
    <!--        <a-button type="primary" icon="import">导入</a-button>-->
    <!--      </a-upload>-->
    <!--      &lt;!&ndash; 高级查询区域 &ndash;&gt;-->
    <!--      <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>-->
    <!--      <a-dropdown v-if="selectedRowKeys.length > 0">-->
    <!--        <a-menu slot="overlay">-->
    <!--          <a-menu-item key="1" @click="batchDel">-->
    <!--            <a-icon type="delete"/>-->
    <!--            <span>删除</span>-->
    <!--          </a-menu-item>-->
    <!--        </a-menu>-->
    <!--        <a-button>-->
    <!--          <span>批量操作</span>-->
    <!--          <a-icon type="down"/>-->
    <!--        </a-button>-->
    <!--      </a-dropdown>-->
    <!--    </div>-->
    <!-- 操作按钮区域 end -->

    <!-- table区域 begin -->
    <div>

      <a-alert type="info" showIcon style="margin-bottom: 16px;">
        <template slot="message">
          <span>已选择</span>
          <a style="font-weight: 600;padding: 0 4px;">{{ selectedRowKeys.length }}</a>
          <span>项</span>
          <a style="margin-left: 24px" @click="onClearSelected">清空</a>
        </template>
      </a-alert>

      <a-table ref="table" size="middle" bordered rowKey="id" class="j-table-force-nowrap" :scroll="{ x: true }"
        :loading="loading" :columns="columns" :dataSource="dataSource" :pagination="ipagination"
        :expandedRowKeys="expandedRowKeys" :rowSelection="{ selectedRowKeys, onChange: onSelectChange }"
        @expand="handleExpand" @change="handleTableChange">

        <!-- 内嵌table区域 begin -->
        <template slot="expandedRowRender" slot-scope="record">
          <a-tabs tabPosition="top">
            <a-tab-pane tab="公用经费支出表" key="cwGyjfzc" forceRender>
              <cw-gyjfzc-sub-table :record="record" />
            </a-tab-pane>
          </a-tabs>
        </template>
        <!-- 内嵌table区域 end -->

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>

        <template slot="imgSlot" slot-scope="text,record">
          <div style="font-size: 12px;font-style: italic;">
            <span v-if="!text">无图片</span>
            <img v-else :src="getImgView(text)" :preview="record.id" alt="" style="max-width:80px;height:25px;" />
          </div>
        </template>


        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button v-else ghost type="primary" icon="download" size="small" @click="downloadFile(text)">
            <span>下载</span>
          </a-button>
        </template>
        <template slot="action" slot-scope="text, record">
          <!-- 只有当状态为"待审批"时才显示审批按钮 -->
          <a v-if="record.state === '待审批'||record.state === '第一人审批同意'" @click="openApprovalModal(record)">审批</a>
          <!-- 如果显示了审批按钮，才显示分隔线 -->
          <a-divider v-if="record.state === '待审批'||record.state === '第一人审批同意'" type="vertical" />
          <a @click="openApprovalMessageDrawer(record.id)">审批详情</a>
        </template>

      </a-table>
    </div>
    <!-- table区域 end -->

    <!-- 审批弹框（包含状态下拉和留言输入） -->
    <a-modal title="审批处理" v-model="approvalModalVisible" ok-text="确认审批" cancel-text="取消" @ok="handleApprovalConfirm"
      @cancel="approvalModalVisible = false">
      <!-- 修复label-col属性类型错误，使用对象形式配置栅格 -->
      <a-form :model="approvalForm" layout="vertical" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <!-- 审批状态下拉框 -->
        <a-form-item label="审批结果">
          <a-select v-model="approvalForm.approvalResult" placeholder="请选择审批结果" style="width: 100%" required>
            <a-select-option value="通过">通过</a-select-option>
            <a-select-option value="驳回">驳回</a-select-option>
          </a-select>
        </a-form-item>
        <!-- 审批留言输入框 -->
        <a-form-item label="审批留言">
          <a-textarea v-model="approvalForm.approvalRemark" placeholder="请输入审批意见（可选）" rows="4"
            style="width: 100%"></a-textarea>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 审批详情抽屉（展示CwApprovalMessageList） -->
    <cw-approval-message-drawer ref="approvalMessageDrawer" @ok="handleApprovalMessageOk"></cw-approval-message-drawer>
    <!-- 表单区域 -->
    <cw-gyjfzc-tj-modal ref="modalForm" @ok="modalFormOk" />

  </a-card>
</template>

<script>

import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import CwGyjfzcTjModal from './modules/CwGyjfzcTjModal'
import CwGyjfzcSubTable from './subTables/CwGyjfzcSubTable'
import JDictSelectTag from '@/components/dict/JDictSelectTag.vue'
import { filterMultiDictText } from '@/components/dict/JDictSelectUtil'
import '@/assets/less/TableExpand.less'
import CwApprovalMessageDrawer from './modules/CwApprovalMessageModal.Style#Drawer.vue'

export default {
  name: 'CwGyjfzcTjList',
  mixins: [JeecgListMixin],
  components: {
    CwApprovalMessageDrawer,
    CwGyjfzcTjModal,
    CwGyjfzcSubTable,
    JDictSelectTag,
  },
  data() {
    return {
      description: '公用经费支出提交表列表管理页面',
      // 表头
      columns: [
        {
          title: '#',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: (t, r, index) => parseInt(index) + 1
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'unit_dictText'
        },
        {
          title: '年度',
          align: 'center',
          dataIndex: 'year'
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'state_dictText'
        },
        {
          title: '提交时间',
          align: 'center',
          dataIndex: 'approvalTime',
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          width: 147,
          scopedSlots: { customRender: 'action' },
        },
      ],
      // 字典选项
      dictOptions: {},
      // 展开的行test
      expandedRowKeys: [],
      url: {
        list: '/cw/cwGyjfzcTj/list',
        delete: '/cw/cwGyjfzcTj/delete',
        deleteBatch: '/cw/cwGyjfzcTj/deleteBatch',
        exportXlsUrl: '/cw/cwGyjfzcTj/exportXls',
        importExcelUrl: '/cw/cwGyjfzcTj/importExcel',
        approval: '/cw/cwGyjfzcTj/approval' // 审批接口
      },
      superFieldList: [],
      approvalModalVisible: false, // 审批弹框显示状态
      currentApprovalRecord: null, // 当前待审批的记录
      approvalForm: {
        approvalResult: '', // 审批结果：通过/驳回
        approvalRemark: '' // 审批留言
      }
    }
  },
  created() {
    this.getSuperFieldList();
  },
  computed: {
    importExcelUrl() {
      return window._CONFIG['domianURL'] + this.url.importExcelUrl
    },
    // 审批接口完整地址
    approvalUrl() {
      return window._CONFIG['domianURL'] + this.url.approval
    }
  },
  methods: {

    // 打开审批弹框
    openApprovalModal(record) {
      this.currentApprovalRecord = record
      // 重置审批表单
      this.approvalForm = {
        approvalResult: '',
        approvalRemark: ''
      }
      this.approvalModalVisible = true
    },

    // 确认审批
    handleApprovalConfirm() {
      // 校验审批结果
      if (!this.approvalForm.approvalResult) {
        this.$message.warning('请选择审批结果（通过/驳回）')
        return
      }

      // 校验记录ID
      if (!this.currentApprovalRecord || !this.currentApprovalRecord.id) {
        this.$message.error('缺少待审批记录信息')
        this.approvalModalVisible = false
        return
      }

      // 发起审批请求
      this.loading = true
      this.$http({
        url: this.approvalUrl,
        method: 'post',
        headers: this.tokenHeader,
        params: {
          id: this.currentApprovalRecord.id,
          approvalResult: this.approvalForm.approvalResult,
          approvalRemark: this.approvalForm.approvalRemark
        }
      }).then(res => {
        if (res.success) {
          this.$message.success('审批操作成功！')
          this.loadData() // 刷新列表
        } else {
          this.$message.error(res.message || '审批操作失败')
        }
      }).catch(err => {
        this.$message.error('审批出错：' + (err.message || err.toString()))
      }).finally(() => {
        this.loading = false
        this.approvalModalVisible = false
      })
    },
    // 打开审批详情抽屉
    openApprovalMessageDrawer(recordId) {
      this.$refs.approvalMessageDrawer.open(recordId)
    },

    // 审批详情抽屉确认回调
    handleApprovalMessageOk() {
      // 可在此处处理刷新逻辑（如刷新当前列表）
    },
    initDictConfig() {
    },

    handleExpand(expanded, record) {
      this.expandedRowKeys = []
      if (expanded === true) {
        this.expandedRowKeys.push(record.id)
      }
    },
    getSuperFieldList() {
      let fieldList = [];
      fieldList.push({ type: 'string', value: 'unit', text: '单位', dictCode: 'unit' })
      fieldList.push({ type: 'string', value: 'state', text: '状态', dictCode: 'state' })
      fieldList.push({ type: 'datetime', value: 'approvalTime', text: '提交时间' })
      fieldList.push({ type: 'string', value: 'year', text: '年度', dictCode: 'year' })
      this.superFieldList = fieldList
    }
  }
}
</script>
<style lang="less" scoped>
@import '~@assets/less/common.less';
</style>